package com.scm.util;

import com.scm.dao.ScmuserMapper;
import com.scm.entity.Scmuser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class  TokenUtil
{
    @Autowired
    private ScmuserMapper userMapper;
    private static final long EXPIRE_TIME = 1800000L;
    private static final String KEY = "aowin";
    private static TokenUtil tokenUtil;

    @PostConstruct
    public void init()
    {
        tokenUtil = this;
        tokenUtil.userMapper = this.userMapper;
    }

    public static String createToken(String id, String username)
    {
        Map<String, Object> header = new HashMap();
        header.put("typ", "JWT");
        header.put("alg", "HS256");

        JwtBuilder builder = Jwts.builder().setHeader(header).setId(id).setExpiration(new Date(System.currentTimeMillis() + 1800000L)).setSubject(username).setIssuedAt(new Date()).signWith(SignatureAlgorithm.HS256, "aowin");

        return builder.compact();
    }

    public static int verify(String token, HttpServletRequest req)
    {
        Claims claims = null;
        try
        {
            claims = (Claims)Jwts.parser().setSigningKey("aowin").parseClaimsJws(token).getBody();

            String id = claims.getId();
            Scmuser user = tokenUtil.userMapper.selectByAccount(id);
            if (user != null)
            {
                req.setAttribute("login", user.getAccount());
                return 1;
            }
            return 0;
        }
        catch (ExpiredJwtException e)
        {
            e.printStackTrace();
            return 2;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return 0;
    }
}
